package com.xinou.daily_report.expand.sso.mini;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.xinou.common.base.exception.BusException;
import com.xinou.common.enumerate.TokenTypeEnum;
import com.xinou.common.util.JwtUtil;
import com.xinou.sso.enumerate.HttpSsoStatusEnum;
import lombok.extern.slf4j.Slf4j;

/**
 * 信鸥 MiniMatchUtil 工具类<br>
 *
 * @author lizhongyuan
 * @date 2021/5/29
 */
@Slf4j
public class MiniMatchUtil extends JwtUtil {

    static boolean checkToken(String jwtToken, String userId) {
        if (StrUtil.isBlank(jwtToken) || StrUtil.isBlank(userId)) {
            throw new BusException(HttpSsoStatusEnum.RE_CODE_NO_HAVE_TOKEN);
        }
        String iss = TokenTypeEnum.TYPE_WEB.getIss();
        JWTVerifier jwtVerifier = JWT
                .require(getAlgorithm())
                .withAudience()
                .withIssuer(iss)
                .build();
        try {
            jwtVerifier.verify(jwtToken);
        } catch (JWTVerificationException ex) {
            if (ex instanceof TokenExpiredException) {
                log.error("Sys:[{}]token 过期", userId);
                throw new BusException(HttpSsoStatusEnum.RE_CODE_EXPIRED_ERROR);
            }
            log.error("Sys:[{}]token 异常 -》[{}]", userId, ex.getMessage());
            return false;
        } catch (Exception e) {
            log.error("Sys:[{}]token 异常 -》[{}]", userId, e.getMessage());
            return false;
        }
        return true;
    }
}
